package main

import (
	"context"
	"fmt"
	"net"
	"os"
	"os/signal"
	"syscall"

	"github.com/devops-smartbot/devops-smartbot/services/integration-service/internal/config"
	"github.com/devops-smartbot/devops-smartbot/services/integration-service/internal/repository"
	"github.com/devops-smartbot/devops-smartbot/services/integration-service/internal/server"
	"github.com/devops-smartbot/devops-smartbot/services/integration-service/internal/service"
	"github.com/devops-smartbot/devops-smartbot/shared/database"
	integrationv1 "github.com/devops-smartbot/devops-smartbot/proto/gen/go/integration/v1"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

func main() {
	// Initialize logger
	logger, _ := zap.NewProduction()
	defer logger.Sync()

	logger.Info("Starting Integration Service...")

	// Load configuration
	cfg := config.Load()

	// Connect to MongoDB
	ctx := context.Background()
	db, err := database.Connect(ctx, cfg.MongoURI, cfg.MongoDB)
	if err != nil {
		logger.Fatal("Failed to connect to MongoDB", zap.Error(err))
	}
	logger.Info("Connected to MongoDB")

	// Initialize repository
	repo := repository.NewIntegrationRepository(db)

	// Initialize service
	integrationService, err := service.NewIntegrationService(repo, logger, cfg.TicketServiceAddr)
	if err != nil {
		logger.Fatal("Failed to create integration service", zap.Error(err))
	}

	// Create gRPC server
	grpcServer := grpc.NewServer()
	integrationGRPCServer := server.NewIntegrationGRPCServer(integrationService, logger)
	integrationv1.RegisterIntegrationServiceServer(grpcServer, integrationGRPCServer)

	// Enable reflection for debugging
	reflection.Register(grpcServer)

	// Start gRPC server
	lis, err := net.Listen("tcp", fmt.Sprintf(":%s", cfg.GRPCPort))
	if err != nil {
		logger.Fatal("Failed to listen", zap.Error(err))
	}

	logger.Info("Integration Service started", zap.String("port", cfg.GRPCPort))

	// Handle graceful shutdown
	go func() {
		if err := grpcServer.Serve(lis); err != nil {
			logger.Fatal("Failed to serve", zap.Error(err))
		}
	}()

	// Wait for interrupt signal
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	logger.Info("Shutting down Integration Service...")
	grpcServer.GracefulStop()
	logger.Info("Integration Service stopped")
}
